package indi.liangli;

import indi.liangli.discovery.IServiceDiscovery;
import org.springframework.util.StringUtils;

import javax.xml.ws.spi.ServiceDelegate;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RemoteProxyInvocationHandler  implements InvocationHandler {


    private IServiceDiscovery serviceDiscovery;

    public RemoteProxyInvocationHandler(IServiceDiscovery serviceDiscovery) {
        this.serviceDiscovery = serviceDiscovery;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //封装目标方法为request对象
        Class clazz = method.getDeclaringClass();
        String methodName = method.getName();
        Request request = new Request(clazz,methodName,args,null);//默认v1.0
        System.out.println(request.toString());

        String serviceName = request.getClazz().getName();
        if(StringUtils.isEmpty(request.getVersion())){
            serviceName +="_v1.0";
        }else{
            serviceName+= "_"+request.getVersion();
        }

        //ip:port
        String serviceAddress = serviceDiscovery.discovery(serviceName);

        RpcNetTransport rpcNetTransport = new RpcNetTransport(serviceAddress);
        return  rpcNetTransport.send(request);

    }
}
